package com.pace.netty.echo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

/**
 * Package: com.pace.netty
 * Description： TODO
 * Author: Forest
 * Date: Created in 2021/4/5 16:37
 * Version: 0.0.1
 * Modified By: duforest
 */
public final class EchoServer {
    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));


    public static void main(String[] args) throws Exception {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;

        }

        // Configure the server.
        // 配置reactor线程池
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        final EchoServerHandler serverHandler = new EchoServerHandler();
        try {
            //创建ServerBootstrap实例
            ServerBootstrap b = new ServerBootstrap();
            //绑定reactor线程池
            b.group(bossGroup, workerGroup)
                    //设置并绑定服务端Channel
                    .channel(NioServerSocketChannel.class)
                    //设置TCP参数，backlog表示等待队列长度
                    .option(ChannelOption.SO_BACKLOG, 100)
                    // 日志
                    .handler(new LoggingHandler(LogLevel.INFO))
                    //绑定事件处理类
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override


                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            if (sslCtx != null) {
                                p.addLast(sslCtx.newHandler(ch.alloc()));

                            }
                            //p.addLast(new LoggingHandler(LogLevel.INFO));
                            //绑定处理事件的Handler，这里可以设置多个
                            p.addLast(serverHandler);

                        }

                    });

            // Start the server.
            // 绑定本是异步操作,这里将其变为同步阻塞
            ChannelFuture f = b.bind(PORT).sync();

            // Wait until the server socket is closed.
            // promise模式，阻塞至channel关闭后才退出
            f.channel().closeFuture().sync();

        } finally {
            // Shut down all event loops to terminate all threads.
            // 优雅退出，释放线程资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

        }

    }
}
